/*
 * 在配置完USB jtag串口后，需要调用一次log或者打印函数才能执行shell。
 *
 */

#include <stdio.h>
#include <inttypes.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_chip_info.h"
#include "esp_flash.h"

//new add file：
#include "pikaScript.h"
#include "esp_log.h"
#include "driver/usb_serial_jtag.h"
#include "esp_vfs_dev.h"
#include "sd_fatfs.h"
#include "pika_hal.h"


#include "aht20_driver.h"


static const char* TAG = "pika";
#define FORCE_ERASE 0





 void eraise_task(void *pvParameter)
{
  //新建一个按键
  pika_dev *dev = pika_hal_open(PIKA_HAL_GPIO, "P0");
 /* 这一块就不能有 否则会溢出
  // pika_hal_GPIO_config cfg = {0};
  // cfg.dir  = PIKA_HAL_GPIO_DIR_IN;
  // cfg.pull = PIKA_HAL_GPIO_PULL_UP;

  // pika_hal_ioctl(dev, PIKA_HAL_IOCTL_CONFIG, &cfg);
  // pika_hal_ioctl(dev, PIKA_HAL_IOCTL_ENABLE);
  */
  int press_time = 0;
  int max_time = 10;

  while (1) 
  {
    uint32_t value = 0;
    pika_hal_read(dev, &value, sizeof(value));
    vTaskDelay(10 / portTICK_PERIOD_MS);

    if (value == 0 )
    {
    press_time ++;
    printf("---%d and %d ===\n",press_time,max_time);
    }
    else
    {
    press_time = 0;
    }

    if(press_time >max_time)
    {
      remove(PIKA_SHELL_SAVE_APP_PATH);
    esp_restart();
    }    
  }
}

//可以用的擦除函数
// void eraise_task(void *pvParameter) {
//   pika_dev *eraise_key = pika_hal_open(PIKA_HAL_GPIO, "P0");
//   pika_hal_GPIO_config cfg = {0};
//   cfg.dir = PIKA_HAL_GPIO_DIR_IN;
//   cfg.pull = PIKA_HAL_GPIO_PULL_UP;

//   int pressed = 0;
//   int max = 10;
//   while (1) {
//     /* sleep 10 ms */
//     vTaskDelay(10 / portTICK_PERIOD_MS);
//     uint32_t value = 0;
//     pika_hal_read(eraise_key, &value, sizeof(value));
//     if (0 == value) {
//       pressed++;
//       printf("[Info] erase key pressed(%d/%d)\n", pressed, max);
//     } else {
//       pressed = 0;
//     }
//     if (pressed >= max) {
//       printf("[Info] erase key pressed(%d/%d)\n", pressed, max);
//       printf("[Info] erase flash\n");
//       remove(PIKA_SHELL_SAVE_APP_PATH);
//       pika_platform_reboot();
//     }
//   }
// }



void print_info(void)
{
    /* Print chip information */
    esp_chip_info_t chip_info;
    uint32_t flash_size;
    esp_chip_info(&chip_info);
    printf("This is %s chip with %d CPU core(s), WiFi%s%s, ",
           CONFIG_IDF_TARGET,
           chip_info.cores,
           (chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "",
           (chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : "");

    unsigned major_rev = chip_info.revision / 100;
    unsigned minor_rev = chip_info.revision % 100;
    printf("silicon revision v%d.%d, ", major_rev, minor_rev);
    if(esp_flash_get_size(NULL, &flash_size) != ESP_OK) {
        printf("Get flash size failed");
        return;
    }

    printf("%" PRIu32 "MB %s flash\n", flash_size / (uint32_t)(1024 * 1024),
           (chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external");
    printf("Minimum free heap size: %" PRIu32 " bytes\n\n", esp_get_minimum_free_heap_size());

}

void app_main(void)
{  
    printf("APP start!\n");

/*init  usb-jtag trans usart*/
    ESP_LOGI(TAG, "init usb_serial_jtag");
        usb_serial_jtag_driver_config_t usb_serial_jtag_config = {
        .rx_buffer_size = 1024 * 8, .tx_buffer_size = 1024};
    usb_serial_jtag_driver_install(&usb_serial_jtag_config);
    esp_vfs_usb_serial_jtag_use_driver();
        ESP_LOGI(TAG, "init usb_serial_jtag done");    

/*init spi and fatfs*/
    sd_fatfs_init() ;

    print_info();


  if(FORCE_ERASE)
  {
    remove(PIKA_SHELL_SAVE_APP_PATH);
  }

  //调用按键擦除
  xTaskCreate(eraise_task, "task_eriase", 1024 * 2, NULL, 10,
              NULL);
  //延时一秒            
  vTaskDelay(1000 / portTICK_PERIOD_MS);

  PikaObj* root = NULL;

  FILE *fp = fopen(PIKA_SHELL_SAVE_APP_PATH,"rb");
  if(fp != NULL)
  {
    fclose(fp);
   
    root = newRootObj("pika_main", New_PikaMain);// 创建根对象,后边必须是 New_PikaMain 否则报错

    obj_linkLibraryFile(root,PIKA_SHELL_SAVE_APP_PATH);
    obj_runModule(root,"main");
     printf("[info] file is load in sd \n");
  }
  else
  {
   
        root = pikaPythonInit();
         printf("load app from framware\n");
  }

    pikaPythonShell(root);
    
    while(1)
    {
        vTaskDelay(1000/portTICK_PERIOD_MS);
    }
}



char pika_platform_getchar() {
  
  while (1) {
    char buff[1] = {0};
    if (usb_serial_jtag_read_bytes(buff, 1, 100) > 0) {
      return buff[0];
    }
    vTaskDelay(1);
  }

}

int pika_platform_putchar(char ch) {
  usb_serial_jtag_write_bytes(&ch, 1, 0);
  return 0;
}


FILE *pika_platform_fopen(const char *filename, const char *modes) {
  return fopen(filename, modes);
}

int pika_platform_fclose(FILE *fp) { return fclose(fp); }

int pika_platform_fseek(FILE *fp, long offset, int whence) {
  return fseek(fp, offset, whence);
}

long pika_platform_ftell(FILE *fp) { return ftell(fp); }

size_t pika_platform_fread(void *ptr, size_t size, size_t count, FILE *fp) {
  return fread(ptr, size, count, fp);
}

size_t pika_platform_fwrite(const void *ptr, size_t size, size_t count,
                            FILE *fp) {
  return fwrite(ptr, size, count, fp);
}


void pika_platform_reboot(void)
{
  //esp_restart();
  abort();
}
